
package com.xayy.health.core.utils;


import com.xayy.health.mgt.model.TreeNode;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 树形结构工具类，如：菜单、部门等
 *
 * @author Houcw
 * @since 1.0.0
 */
public class TreeUtils {

    /**
     * 根据pid，构建树节点
     */
    public static <T extends TreeNode> List<T> build(List<T> treeNodes, Long pid) {
        List<T> treeList = new ArrayList<>();
        for(T treeNode : treeNodes) {
            if (pid.equals(treeNode.getPid())) {
                treeList.add(findChildren(treeNodes, treeNode));
            }
        }

        return treeList;
    }

    /**
     * 查找子节点
     */
    private static <T extends TreeNode> T findChildren(List<T> treeNodes, T rootNode) {
        for(T treeNode : treeNodes) {
            if(rootNode.getId().equals(treeNode.getPid())) {
                rootNode.getChildren().add(findChildren(treeNodes, treeNode));
            }
        }
        return rootNode;
    }

    /**
     * 构建树节点
     */
    public static <T extends TreeNode> List<T> build(List<T> treeNodes) {
        List<T> result = new ArrayList<>();

        //list转map
        Map<Long, T> nodeMap = new LinkedHashMap<>(treeNodes.size());
        for(T treeNode : treeNodes){
            nodeMap.put(treeNode.getId(), treeNode);
        }

        for(T node : nodeMap.values()) {
            T parent = nodeMap.get(node.getPid());
            if(parent != null && !(node.getId().equals(parent.getId()))){
                parent.getChildren().add(node);
                continue;
            }

            result.add(node);
        }

        return result;
    }

    /**
     * 获取该树下的所有子节点
     */
    public static List<TreeNode> getAllChildren(List<TreeNode> nodeTrees, Long pid) {

        List<TreeNode> result = new ArrayList();
        if(nodeTrees == null || nodeTrees.size() == 0){
            return result;
        }
        for (TreeNode node : nodeTrees) {
            if (node.getPid().equals(pid)){
                result.addAll(findLeafNodes(node));
                break;
            } else {
                List<TreeNode> childList = node.getChildren();
                for (TreeNode childNode : childList) {
                    result.addAll(findLeafNodes(childNode));
                    break;
                }
            }
        }
        return result;
    }

    public static List<TreeNode> findLeafNodes(TreeNode node) {
        List<TreeNode> result = new ArrayList<>();
        if (node == null) {
            return result;
        }
        List<TreeNode> children = node.getChildren();

        if (children == null || children.size() == 0) {
            result.add(node);
        } else {
            for (TreeNode child : children) {
                result.addAll(findLeafNodes(child));
            }
        }
        return result;
    }

}
